package com.qf.adapter;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.qf.bean.City;
import com.qf.homeproject.R;

public class CityListAdapter extends BaseAdapter implements SectionIndexer
{
	private Context context;
	private List<City> datas;

	public CityListAdapter(Context context, List<City> datas)
	{
		this.context = context;
		this.datas = datas;
	}

	@Override
	public int getCount()
	{
		// TODO Auto-generated method stub
		return datas.size();
	}

	@Override
	public Object getItem(int position)
	{
		// TODO Auto-generated method stub
		return datas.get(position);
	}

	@Override
	public long getItemId(int position)
	{
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		// Log.i("info", "getView执行的次数");
		View view = LayoutInflater.from(context).inflate(
				R.layout.item_listview, null);
		TextView nameTv = (TextView) view
				.findViewById(R.id.textView_item_username);
		TextView letterTv = (TextView) view
				.findViewById(R.id.tvId_first_letter);
		nameTv.setText(datas.get(position).getCityName() + "");
		String id = datas.get(position).getCityName();
		String a = "1";
		// 每个字母分组中的首个position所对应的textView_item_firstLetter控件显示或隐藏

		int section = getSectionForPosition(position);
		if (position == getPositionForSection(section) && position > 3)
		{
			letterTv.setVisibility(View.VISIBLE);
			letterTv.setText(datas.get(position).getFirstLetter());
		}
		else
		{
			letterTv.setVisibility(View.GONE);
		}

		if (position == 0)
		{
			letterTv.setVisibility(View.VISIBLE);
			letterTv.setText("热门城市");
		}
		return view;
	}

	@Override
	public Object[] getSections()
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int getPositionForSection(int sectionIndex)
	{
		for (int i = 4; i < getCount(); i++)
		{
			String firstLetter = datas.get(i).getFirstLetter();
			// Log.i("info", "首字母为:" + firstLetter);
			int firstChar = firstLetter.charAt(0);
			if (firstChar == sectionIndex) { return i; }
		}
		return -1;
	}

	@Override
	public int getSectionForPosition(int position)
	{
		if (position > 3) {

		return datas.get(position).getFirstLetter().charAt(0); }
		return -1;

	}

	public void reLoadListView(List<City> dataList, boolean isClear)
	{
		if (isClear)
		{
			datas.clear();
		}
		datas.addAll(dataList);
		notifyDataSetChanged();
	}
}
